package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

type CoachRepository interface {
	Create(coach *model.Coach) error
	Update(coach *model.Coach) error
	Delete(id uint) error
	GetByID(id uint) (*model.Coach, error)
	GetByPhone(phone string) (*model.Coach, error)
	List(page, pageSize int) ([]model.Coach, int64, error)
}

type coachRepository struct {
	db *gorm.DB
}

func NewCoachRepository(db *gorm.DB) CoachRepository {
	return &coachRepository{db: db}
}

func (r *coachRepository) Create(coach *model.Coach) error {
	return r.db.Create(coach).Error
}

func (r *coachRepository) Update(coach *model.Coach) error {
	return r.db.Save(coach).Error
}

func (r *coachRepository) Delete(id uint) error {
	return r.db.Delete(&model.Coach{}, id).Error
}

func (r *coachRepository) GetByID(id uint) (*model.Coach, error) {
	var coach model.Coach
	err := r.db.First(&coach, id).Error
	return &coach, err
}

func (r *coachRepository) GetByPhone(phone string) (*model.Coach, error) {
	var coach model.Coach
	err := r.db.Where("phone = ?", phone).First(&coach).Error
	return &coach, err
}

func (r *coachRepository) List(page, pageSize int) ([]model.Coach, int64, error) {
	var coaches []model.Coach
	var total int64

	offset := (page - 1) * pageSize

	if err := r.db.Model(&model.Coach{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := r.db.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&coaches).Error
	return coaches, total, err
}
